#include <iostream>
#include <string>
#include <unordered_map>
#include "../user.pb.h"  // 确保这里的路径是正确的，并且文件内的命名空间已更改为User
#include "RpcApplication.h"
#include "RpcConfig.h"
#include "Rpcserver.h"

class UserService : public User::UserServiceRpc { 
private:
    std::unordered_map<std::string, std::string> user_data; // 用于存储用户名和密码

public:
    // 本地登录方法，根据新逻辑修改
    bool Login(const std::string& name, const std::string& pwd) {
        auto it = user_data.find(name);
        if (it != user_data.end() && it->second == pwd) {
            return true;
        }
        return false;
    }

    // 重写基类 UserServiceRpc 的 Login 方法
    void Login(::google::protobuf::RpcController* controller,
               const ::User::LoginRequest* request,
               ::User::LoginResponse* response,
               ::google::protobuf::Closure* done) {
        std::string name = request->name();
        std::string pwd = request->pwd();

        bool login_result = Login(name, pwd);

        User::ResultCode *code = response->mutable_result();
        code->set_errcode(login_result ? 0 : 1);  // 设置错误码
        code->set_errmsg(login_result ? "" : "Login failed");  // 设置错误信息
        response->set_success(login_result);

        done->Run();
    }

    // 本地注册方法，根据新逻辑修改
    bool Register(const std::string& name, const std::string& pwd) {
        auto it = user_data.find(name);
        if (it != user_data.end()) {
            return false; // 用户名已存在
        }
        user_data[name] = pwd;
        return true;
    }

    // 重写基类 UserServiceRpc 的 Register 方法
    void Register(::google::protobuf::RpcController* controller,
                  const ::User::RegisterRequest* request,
                  ::User::RegisterResponse* response,
                  ::google::protobuf::Closure* done) {
        std::string name = request->name();
        std::string pwd = request->pwd();

        bool register_result = Register(name, pwd);

        User::ResultCode *code = response->mutable_result();
        code->set_errcode(register_result ? 0 : 1);  // 设置错误码
        code->set_errmsg(register_result ? "" : name+" User already exists");  // 设置错误信息
        response->set_success(register_result);

        done->Run();
    }
};

int main(int argc, char **argv) {
    RpcApplication::Init(argc, argv);
    EasyRpc::RpcServer server;
    // std::cout<<"notify service"<<std::endl;
    server.NotifyService(new UserService());
    server.Run();
    return 0;
}